package com.totcy.atom.view.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.widget.ImageView;

import com.totcy.atom.BuildConfig;
import com.totcy.atom.R;
import com.totcy.atom.adapter.CommonFragmentAdapter;
import com.totcy.atom.bean.BannerBean;
import com.totcy.atom.presenter.BannerPresenter;
import com.totcy.atom.presenter.contract.BannerContract;
import com.totcy.atom.utils.glide.GlideUtil;
import com.totcy.atom.view.activity.WebViewActivity;
import com.totcy.baselibrary.utils.StatusBarUtil;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * description : 分类新闻列表
 *
 * @author : Totcy
 * @date : 2018/2/2 11:03
 * @update : 2018/10/25
 */

public class HomeNewsTypeFragment extends BaseFragment<BannerContract.View, BannerPresenter> implements OnBannerListener, BannerContract.View {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.toolbar_layout)
    CollapsingToolbarLayout toolbarLayout;
    @BindView(R.id.tabLayout)
    TabLayout tabLayout;
    @BindView(R.id.app_bar)
    AppBarLayout appBar;
    @BindView(R.id.vp_newsList)
    ViewPager viewPager;
    @BindView(R.id.bannerView)
    Banner banner;

    private List<BaseFragment> fragmentList = new ArrayList<>();
    private List<BannerBean> images = new ArrayList<>();
    private String[] typeArray = new String[]{"Android", "iOS", "前端", "App","休息视频", "拓展资源", "瞎推荐" };

    @Override
    public int getLayoutId() {
        return R.layout.fragment_home_news_type;
    }

    @SuppressLint("CheckResult")
    @Override
    public void initView(Bundle savedInstanceState) {
        StatusBarUtil.setPaddingSmart(getActivity(), toolbar);
        //toolbar.setAlpha(0f);

        fragmentList.clear();

        Observable.fromArray(typeArray).subscribe(new Consumer<String>() {
            @Override
            public void accept(String type) throws Exception {
                tabLayout.addTab(tabLayout.newTab().setText(type));
                fragmentList.add(new GankNewsFragment().setFragmentTitle(type));
            }
        });


        viewPager.setAdapter(new CommonFragmentAdapter(getChildFragmentManager(), fragmentList));
        tabLayout.setupWithViewPager(viewPager);
        //appBar
        appBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                //LogUtils.logd("verticalOffset = " + verticalOffset);
                toolbar.getBackground().mutate().setAlpha(scrollListen((float) verticalOffset / (toolbar.getLayoutParams().height - banner.getLayoutParams().height)));
            }
        });

        initBanner();
        //获取banner数据
        getPresenter().getBannerList();

        //测试全埋点 过滤掉自己add的监听方法
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    /**
     * banner初始化
     */
    private void initBanner() {
        //设置banner样式 标题 圆形指示器水平显示
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE);
        //圆形指示器居右
        banner.setIndicatorGravity(BannerConfig.RIGHT);
        //设置图片加载器
        banner.setImageLoader(new ImageLoader() {
            @Override
            public void displayImage(Context context, Object path, ImageView imageView) {
                BannerBean bannerBean = (BannerBean) path;
                GlideUtil.loadImage(getActivity(), bannerBean.getImage_url(), imageView);
            }
        });
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.Accordion);
        banner.setOnBannerListener(this);
    }

    @Override
    public void OnBannerClick(int position) {
        Bundle bundle = new Bundle();
        bundle.putString("url", images.get(0).getAction_url());
        bundle.putString("title", BuildConfig.APP_NAME);
        openActivity(WebViewActivity.class, bundle);
    }

    @SuppressLint("CheckResult")
    @Override
    public void onBannerData(final List<BannerBean> images) {
        this.images.clear();
        this.images.addAll(images);
        Observable.create(new ObservableOnSubscribe<List<String>>() {
            @Override
            public void subscribe(ObservableEmitter<List<String>> e) throws Exception {
                List<String> list = new ArrayList<String>();
                for (BannerBean bannerBean : images) {
                    list.add(bannerBean.getDescription());
                }
                e.onNext(list);
            }
        })
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<String>>() {
                    @Override
                    public void accept(@NonNull List<String> s) throws Exception {
                        //设置图片集合
                        banner.setImages(images);
                        //设置标题集合（当banner样式有显示title时）
                        banner.setBannerTitles(s);
                        //banner设置方法全部调用完毕时最后调用
                        banner.start();
                    }
                });
    }

    private static final float MAX_ALPHA = 255.00000f;

    /**
     * 监听滚动事件的相关逻辑
     */
    private int scrollListen(float percent) {
        int mAlpha = (int) (percent * MAX_ALPHA);
        if (mAlpha > 255) {
            mAlpha = 255;
        }
        if (mAlpha < 0) {
            mAlpha = 0;
        }
        return mAlpha;
    }
}
